#include	"Uigp/igp.h"
#include	"Ucamera/Pt2dType.h"
#include    "Umath/Matrix2Type.h"
#include    "VrLine.h"
#include    "VrCell.h"
#include	"Uln/LnType.h"


void 
vrCell_line( pt2dA_type *apt, int i0,vrCell_type *vc )
{
	int i;
	float degree = 0;
	float nx = 0;
	float ny = 0;
	int k = 0;
	vc->index = i0;
	vc->p = apt->p[i0].p;

	vc->n = 0;
	for( i = 0; i < apt->nP ; i++ )
	{
		if( i != i0 )	
		{
			vrLine_compute( &vc->vl[vc->n] , &apt->p[i0].p , &apt->p[i].p );

			vc->vl[k].index = i;

			vc->n++;

			k++;
		}
	}
}


pt2dA_type* 
vrCell_to_apt( vrCell_type *vc )
{
	pt2dA_type *apt;
	apt = pt2dA_alloc( vc->n );
	apt->type = PT2D_4V;

	pt2d_type *pt = &apt->p[apt->nP++];
	pt->p = vc->p;
	pt->n.x = 0;
	pt->n.y = 0;

	for(int i = 0 ; i < vc->n ; i++ )
	{
		pt2d_type *pt = &apt->p[apt->nP++];
		pt->p = vc->vl[i].p;
		pt->n = vc->vl[i].n;
	}
	return( apt );
}

int
vrCell_filter( vrCell_type *vc )
{
	int	i;
	
	for( i = 0; i < vc->n ; ){
		if( vrCell_filter_1( vc, i) < 0 )
			i++;
	}
return 1;
}


static int
vrCell_filter_1( vrCell_type *vc, int i0)
{
    vrLine_type	 *vl0,	*vl1,	*vl;
	if(i0 == 0)   
	{
		vl  = &vc->vl[i0];
		vl0 = &vc->vl[vc->n - 1];
		vl1 = &vc->vl[i0 + 1];
	}
	else if(i0 == vc->n)    
	{
		vl  = &vc->vl[i0];
		vl0 = &vc->vl[i0 -1];
		vl1 = &vc->vl[0];
	}
	else
	{
		vl  = &vc->vl[i0];
		vl0 = &vc->vl[i0 - 1];
		vl1 = &vc->vl[i0 + 1];
	}
	vec2f_type p;

	float deg = vl1->degree - vl0->degree;
	if(deg < 180)
		return -1;
	int sharePoint;

     sharePoint = vrLine_SharePoint( vl0,vl1,&p );
     if(sharePoint != 1)
		 return -1;

	int vrSide;

    vrSide = vrLine_side( vl, &p );

	if( vrSide != 1 )
		return( -1 );

	vc->n--;
	
	int i=0;
	for( i = i0 ; i < vc->n ; i++ )
		vc->vl[i] = vc->vl[i+1];

	return 1;
}


void 
vrCell_create( pt2dA_type *apt, int i0, vrCell_type *vc )
{
	vrCell_line( apt, i0, vc );

	vrCell_order( vc );
}


void 
vrCell_order( vrCell_type *vc )
{
	for(int i = 0 ; i < vc->n ; i++)
	{
		printf("%d) %f \n",i,vc->vl[i].degree);
	}

	int x;
	int y;

	// Bubble sort method.
	vrLine_type holder;
	for (x = 0; x < vc->n; x++)
		for (y = 0; y < vc->n - 1; y++)
			if (vc->vl[y].degree > vc->vl[y + 1].degree)
			{
				holder = vc->vl[y + 1];
				vc->vl[y + 1] = vc->vl[y];
				vc->vl[y] = holder;
			}

	printf("After Sort\n\n");
	for(int i = 0 ; i < vc->n ; i++)
	{
		printf("%d) %.2f \n",i,vc->vl[i].degree);
	}

	printf("\n\n\n");
}



void
vrCell_write( vrCell_type *vc, char *file  )
{
	int	i;
	vec2f_type	av[100];
	vec2f_type ctr;

	ln_type	*lnL;

	for( i = 0; i < vc->n ; i++ ){
		av[i].x = vc->vl[i].p.y;
		av[i].y = vc->vl[i].p.x;

	}

	lnL_from_points( av, vc->n, 1, &ctr, &lnL );

	lnL_write( &ctr, lnL, file );
}
